import { getInfoApi, getAddresseeApi, getCartLenApi } from "../../api";

const actions = {
  // 页面加载获取基本信息
  firstGetInfo(context) {
    localStorage.setItem("isLogin", "");
    getInfoApi(
      (response) => {
        if (response.data.status === 1) {
          context.dispatch("getAddressee");
          localStorage.setItem("isLogin", "true");
          context.commit("FIRSTGETINFOR", { status: 1, data: response.data.data });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },

  // 获取基本个人信息
  getInfo(context) {
    getInfoApi(
      (response) => {
        if (response.data.status === 1) {
          context.commit("GETINFOR", response.data.data);
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },

  // 获取收货信息
  getAddressee(context) {
    getAddresseeApi(
      (response) => {
        if (response.data.status !== 1) return console.log("获取收货信息失败");
        let data = {
          name: response.data.data.name || "",
          phone: response.data.data.phone || "",
          address: response.data.data.address || "",
        }
        context.commit("GETADDRESSEE", data);
      },
      (err) => {
        console.log(err);
      }
    );
  },

  // 获取购物车长度
  getCartLen(context) {
    getCartLenApi(
      (response) => {
        if (response.data.status === 1) {
          context.commit("GETCARTLEN", response.data.len);
        }
      },
      (err) => {
        console.log(err);
      }
    )
  }
}
const mutations = {
  //登录状态改为 true
  LOGIN(state) {
    state.isLogin = true;
  },

  //修改登录状态为 true 获取个人基础信息
  FIRSTGETINFOR(state, value) {
    state.isLogin = !!value.status;
    state.info = value.data;
  },

  // 获取个人基础信息
  GETINFOR(state, value) {
    state.info = value;
  },

  //登录状态改为 false
  QUIT(state) {
    localStorage.setItem("token", "");
    localStorage.setItem("isLogin", "");
    state.isLogin = false;
    state.info = {};
    state.addressee = {};
  },
  // 获取收货地址信息
  GETADDRESSEE(state, value) {
    state.addressee = value;
  },

  // 获取购物车长度
  GETCARTLEN(state, value) {
    state.cartLen = value;
  }
}

const getters = {

}

const state = {
  isLogin: false,
  // message: "",
  info: {},
  addressee: {},
  cartLen: 0,
}

export default {
  namespaced: true,
  actions,
  mutations,
  getters,
  state
}